package czy.demo.controller;

import czy.demo.util.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/mail")
public class MailController {

    private static final Logger logger = LoggerFactory.getLogger(MailController.class);

    /* 收件人地址 */
    private static Address to = null;

    static {
        try{
            to = new InternetAddress("1253665625@qq.com");
        }catch (AddressException ex){
            ex.printStackTrace();
        }
    }

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private MD5Util md5Util;

    /* spring的邮件工具类 */
    @Autowired
    private JavaMailSenderImpl sender;

    /* 发送简单文本邮件 */
    @PostMapping("/sendText")
    public String sendText(@RequestBody String content)throws MessagingException {

        /* 获取消息 */
        MimeMessage message =  this.sender.createMimeMessage();

        /* 虽然配置smtp邮件服务时，用户名就是邮箱名称，但是这里必须设置发件人，而且必须与邮件服务用户名一致 */
        message.setFrom(from);

        /* 设置收件人 */
        message.setRecipient(Message.RecipientType.TO,to);

        /* 这些都没有用 */
        message.setContentID(UUID.randomUUID().toString());
        message.setContentLanguage(new String[]{"zh"});
        message.setContentMD5(md5Util.getMD5(content));
        message.setDescription("这是邮件描述");

        /* 设置文件名，会把content作为一个附件发送，正文不变 */
        message.setFileName("这是文件名");

        /* 貌似只有邮件主题、时间是有效的 */
        message.setSentDate(new Date(System.currentTimeMillis()-3600*1000));
        message.setSubject("测试");

        /* 设置邮件文本内容 */
        message.setText(content);

        this.sender.send(message);

        return "邮件发送成功";
    }

    /**
     * 发送带附件的邮件
     * @param subject：主题
     * @param content：正文
     * @param files：附件
     */
    @PostMapping("/sendAttach")
    public String sendAttach(
            @RequestParam("subject") String subject,
            @RequestParam("content") String content,
            @RequestParam("files") MultipartFile[] files
    )throws MessagingException,IOException {

        MimeMessage message = this.sender.createMimeMessage();

        /* 需要使用帮助类来设置附件，自己设置附件很坑 */
        MimeMessageHelper helper = new MimeMessageHelper(message,true);
        helper.setFrom(from);
        helper.setTo(from);
        helper.setSubject(subject);

        /* 只有附件，没有正文会报错 */
        helper.setText(content);

        for(MultipartFile file:files){
            /* 附件这个创建InputStreamResource时不可以使用文件流，只能使用字节流 */
            helper.addAttachment(file.getOriginalFilename(),new ByteArrayResource(file.getBytes()),file.getContentType());
        }

        this.sender.send(message);
        return "邮件发送成功";
    }

}
